import Ux from "ux";
import Ch from "../channel";
import Do from "./wf.action.data";
import Fn from '../functions';

export default (reference) => ({
    yiQueue: () => Ch.yiAssist(reference).then(state => {
        state.$ready = true;
        /*
         * 外层传入 $query，保留分页、排序、列参数
         * $query 是查询专用的，在更新时更新查询条件
         * $queryDefault 是默认查询条件，所有查询操作都基于该查询条件处理
         */
        const grid = Ux.fromHoc(reference, "grid");
        const options = grid.options ? grid.options : {};
        state.options = Ux.clone(options);
        const code = options[Fn.Opt.DYNAMIC_CODE];

        /*
         * New workflow for dynamic qr extracting
         * GET /api/ui/list-qr/:code
         * New variable $qbe for dropdown view
         */
        if (code) {
            state.$queryDefault = Ux.clone(grid.query);
            state.$query = Ux.clone(grid.query);
            state.$qbeDefault = code;           // code 的默认值
            /*
             * __state 还原
             */
            const {$router} = reference.props;
            const __state = $router.__state();
            if (Ux.isNotEmpty(__state)) {
                Ux.dgDebug(__state, "状态还原");
                Object.assign(state, __state);
            }
            reference.setState(state);
        } else {
            throw new Error("工作流的列表 code 丢失")
        }
    }),
    // 新方法 yoWorkflow
    yoQueue: () => {
        const inherits = Ch.yoAmbient(reference);
        const grid = Ch.yoGrid(reference);
        // config -> grid ( FastList )
        inherits.config = grid;
        /*
         * grid -> parameter / record
         * workflow combine
         * 1) 将 parameter 和 $workflow 合并（parameter有更高优先级）
         * 2) 将 record 追加到 $workflow 中
         * 计算 synonym 到 $synonym
         */
        const {parameter = {}, record = {}, options = {}} = grid;
        let {$workflow = {}} = reference.props;
        $workflow = Ux.clone($workflow);
        Object.assign($workflow, parameter);
        $workflow.record = record;
        inherits.$workflow = $workflow;

        const synonym = Do.configUi($workflow, "synonym");
        if (Ux.isNotEmpty(synonym)) {
            inherits.$synonym = synonym;
        }

        let {
            $query = {},
            $refresh,
        } = reference.state;
        inherits.$refresh = $refresh;
        inherits.$query = $query;

        inherits.rxSearch = (query) => {
            const {$qbe} = reference.state;
            return Ux.ajaxPost(`${options[Fn.Opt.AJAX_SEARCH_URI]}?QBE=:qbe`, {
                qbe: $qbe,
                $body: query
            });
        };
        return inherits;
    },
})